import 'package:animated_digit/animated_digit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/base/widget/base_get_builder.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/main/main_logic.dart';
import 'package:flutter_09_game/pages/promotion/promotion_logic.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/user/model/app_user_info_model.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/image/image_view.dart';
import 'package:flutter_09_game/widgets/widget_user_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../config/app_color.dart';
import 'profile_logic.dart';

class ProfilePage extends StatelessWidget {
  ProfilePage({super.key});

  final ProfileLogic logic = Get.put(ProfileLogic());

  @override
  Widget build(BuildContext context) {
    double spacing = (1.sw - 56.w - 90.w * 3) ~/ 2 * 1.0;
    return BaseGetBuilder<ProfileLogic>(
      // bodyTopViewBuilder: (_) {
      //   return _buildHeader();
      // },
      builder: (_) {
        return SingleChildScrollView(
          physics: const ClampingScrollPhysics(),
          padding: EdgeInsets.only(bottom: 16.w),
          child: Column(
            children: [
              _buildTopView(),
              // 24.verticalSpaceFromWidth,
              // SizedBox(
              //     height: 30.w,
              //     child: Align(
              //       alignment: Alignment.centerLeft,
              //       child: Text(
              //         LocaleKeys.operations.tr,
              //         style: TextStyle(
              //             color: AppColor.textPrimary.withOpacity(0.94),
              //             fontSize: 16.sp,
              //             fontWeight: FontWeight.w500),
              //       ),
              //     )).marginOnly(left: 16.w),
              24.verticalSpaceFromWidth,
              Container(
                  margin: EdgeInsets.symmetric(
                    horizontal: 16.w,
                  ),
                  padding:
                      EdgeInsets.symmetric(horizontal: 12.w, vertical: 16.w),
                  decoration: BoxDecoration(
                    color: AppColor.navBgColor,
                    borderRadius: BorderRadius.circular(12.w),
                  ),
                  child: Wrap(
                    runSpacing: 20.w,
                    spacing: spacing,
                    children: [
                      // _buildItems(
                      //     icon: Assets.mineItemUser,
                      //     title: LocaleKeys.uid.tr,
                      //
                      //     onClick: () {}),
                      _buildItems(
                          icon: Assets.mineItemDetail,
                          title: LocaleKeys.accountChangeDetails.tr,
                          onClick: () {
                            Get.toNamed(AppRoutes.depositRecordPage);
                          }),
                      _buildItems(
                          icon: Assets.mineItemRecord,
                          title: LocaleKeys.betRecord.tr,
                          onClick: () {
                            Get.toNamed(AppRoutes.profileBetRecordPage);
                          }),
                      _buildItems(
                          icon: Assets.mineItemBuy,
                          title: LocaleKeys.buyCrypto.tr,
                          onClick: () {
                            Get.toNamed(AppRoutes.homeDownloadCenterPage);
                          }),

                      _buildItems(
                          icon: Assets.mineItemLanguage,
                          title: LocaleKeys.multiLanguage.tr,
                          onClick: () {
                            Get.toNamed(AppRoutes.profileLanguagePage);
                          }),

                      _buildItems(
                          icon: Assets.mineItemHelp,
                          title: LocaleKeys.helpGuide.tr,
                          onClick: () {
                            Get.toNamed(AppRoutes.homeCoursePage);
                          }),
                      _buildItems(
                          icon: Assets.mineItemSafe,
                          title: LocaleKeys.securityCenter.tr,
                          onClick: () {
                            Get.toNamed(AppRoutes.profileSafetyCenterPage);
                            // profileSafetyCenterPage
                          }),
                      _buildItems(
                          icon: Assets.mineItemShare,
                          title: LocaleKeys.shareWithFriends.tr,
                          onClick: () {
                            Get.find<MainLogic>().changeIndex(1);

                            Get.find<PromotionLogic>()
                                .tabController
                                .animateTo(2);
                          }),
                      // _buildItems(
                      //     icon: Assets.mineItemDress,
                      //     title: LocaleKeys.switchTheme.tr,
                      //     onClick: () {}),
                    ],
                  ))
            ],
          ),
        );
      },
    );
  }

  Widget _buildHeader() {
    return Obx(() {
      AppUserInfoModelUser? user = AppUserManager().user.value;
      return Row(
        children: [
          // WidgetUserHeader(userAvatar: userAvatar, isOnline: isOnline, username: username, memberCount: memberCount, userIdentity: userIdentity, withdrawAddress: withdrawAddress)
          ImageView(
            imageUrl: user?.avatar,
            radius: 30.w,
          ),
          12.horizontalSpace,
          Expanded(
              child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                user?.username ?? '',
                style: TextStyle(
                    color: AppColor.textPrimary.withOpacity(0.94),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600),
              ),
              3.verticalSpaceFromWidth,
              GestureDetector(
                onTap: () {
                  if ((user?.identity ?? '').isNotEmpty) {
                    Clipboard.setData(
                        ClipboardData(text: user?.identity ?? ''));
                    // Fluttertoast.showToast(msg: LocaleKeys.copySuccess.tr);
                    LoadingUtils.showToast(LocaleKeys.copySuccess.tr);
                    // }
                  }
                },
                child: Row(
                  children: [
                    Text(
                      LocaleKeys.uid.tr,
                      style: TextStyle(
                          color: AppColor.textPrimary.withOpacity(0.7),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400),
                    ),
                    4.horizontalSpace,
                    Text(
                      user?.identity ?? '',
                      style: TextStyle(
                          color: AppColor.textPrimary.withOpacity(0.94),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w600),
                    ),
                    4.horizontalSpace,
                    AutoImage(
                      Assets.mineCopy,
                      width: 16.w,
                    )
                  ],
                ),
              ),
              3.verticalSpaceFromWidth,
              Row(
                children: [
                  Text(
                    LocaleKeys.betAddress.tr,
                    style: TextStyle(
                        color: AppColor.textPrimary.withOpacity(0.94),
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500),
                  ),
                  4.horizontalSpace,
                  GestureDetector(
                    onTap: () {
                      clickSetWithdrawAddress();
                    },
                    child: Text(
                      UtilsOther.formatWithdrawAddress(user?.withdrawAddress),
                      //    LocaleKeys.notBound.tr,
                      style: TextStyle(
                          color: AppColor.primary,
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ],
              )
            ],
          )),
          12.horizontalSpace,
          CommonButton(
            title: LocaleKeys.editProfile.tr,
            enable: false,
            alwaysCanClick: true,
            width: 76.w,
            fontSize: 12.sp,
            height: 32.w,
            onClick: () {
              Get.toNamed(AppRoutes.profileEditPage);
            },
          ),
          // 12.horizontalSpace,
          // GestureDetector(
          //   onTap: () {
          //     AppUserManager().logout();
          //   },
          //   child: AutoImage(
          //     Assets.commonShareBtn,
          //     width: 32.w,
          //   ),
          // )
        ],
      );
    });
  }

  Widget _buildTopView() {
    return Container(
      padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
          bottom: 16.w,
          top: ScreenUtil().statusBarHeight + 16.w),
      decoration: BoxDecoration(
          color: AppColor.navBgColor,
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(
                30.w,
              ),
              bottomRight: Radius.circular(
                30.w,
              ))),
      child: Column(
        children: [
          _buildHeader(),
          16.verticalSpaceFromWidth,
          Container(
              width: double.infinity,
              height: 176.w,
              padding: EdgeInsets.all(12.w),
              decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage(
                      Assets.mineBankBg,
                    ),
                    fit: BoxFit.fill),
              ),
              child: Obx(() {
                return Column(
                  children: [
                    SizedBox(
                      height: 32.w,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            LocaleKeys.assetOverview.tr,
                            style: TextStyle(
                                color: AppColor.textPrimary.withOpacity(0.94),
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w500),
                          ),
                          GestureDetector(
                            onTap: () {
                              AppUserManager().loadWalletData(showLoad: true);
                            },
                            child: AutoImage(
                              Assets.commonRefreshBtn,
                              width: 32.w,
                            ),
                          )
                        ],
                      ),
                    ),
                    8.verticalSpaceFromWidth,
                    Container(
                      height: 0.5,
                      color: AppColor.textPrimary.withOpacity(0.3),
                    ),
                    _buildWalletItemTitle(
                        Text(
                          LocaleKeys.currency.tr,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: AppColor.textPrimary.withOpacity(0.7),
                              fontSize: 12.sp),
                        ),
                        LocaleKeys.walletBalance.tr,
                        LocaleKeys.commissionBalance.tr),
                    ...AppUserManager().walletList.map((value) {
                      return _buildWalletItem(
                          Row(
                            children: [
                              AutoImage(
                                UtilsOther().getAmountTagIcon(value.symbol),
                                width: 20.w,
                              ),
                              4.horizontalSpace,
                              Text(value.symbol ?? '',
                                  style: TextStyle(
                                      color: AppColor.textPrimary
                                          .withOpacity(0.94),
                                      fontWeight: FontWeight.w600,
                                      fontSize: 16.sp))
                            ],
                          ),
                          value.balance ?? 0,
                          value.rebateBalance ?? 0,
                          isTitle: false);
                    }),
                  ],
                );
              })),
          16.verticalSpaceFromWidth,
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                  child: _buildRowBtn(
                bgIcon: Assets.mineDepositBg,
                icon: Assets.mineDeposit,
                title: LocaleKeys.walletRecharge.tr,
                onClick: () {
                  Get.find<MainLogic>().changeIndex(2);
                },
              )),
              12.horizontalSpace,
              Expanded(
                  child: _buildRowBtn(
                bgIcon: Assets.mineWithdrawBg,
                icon: Assets.mineWithdraw,
                title: LocaleKeys.fundWithdrawal.tr,
                onClick: () {
                  Get.toNamed(AppRoutes.promotionWithdrawPage);
                },
              )),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildWalletItem(Widget title, int centerCount, int bottomCount,
      {bool isTitle = true}) {
    return Row(
      children: [
        SizedBox(width: 70.w, child: title),
        12.horizontalSpace,
        Expanded(
          child: SizedBox(
            height: 36.w,
            child: Center(
              // child: Text(
              //   centerStr, //.formatAmount()
              //   style: TextStyle(
              //       color: AppColor.textPrimary.withOpacity(0.94),
              //       fontWeight: isTitle ? FontWeight.w400 : FontWeight.w600,
              //       fontSize: isTitle ? 12.sp : 16.sp),
              // ),
              child: AnimatedDigitWidget(
                value: centerCount / 1000000.0,
                textStyle: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.94),
                  fontWeight: isTitle ? FontWeight.w400 : FontWeight.w600,
                  fontSize: isTitle ? 12.sp : 16.sp,
                  letterSpacing: -0.38,
                ),
                fractionDigits: 2,
                enableSeparator: true,
              ),
            ),
          ),
        ),
        12.horizontalSpace,
        Expanded(
          child: SizedBox(
            height: 36.w,
            child: Center(
              // child: Text(
              //   bottomStr,
              //   style: TextStyle(
              //       color:
              //           AppColor.textPrimary.withOpacity(isTitle ? 0.7 : 0.94),
              //       fontWeight: isTitle ? FontWeight.w400 : FontWeight.w600,
              //       fontSize: isTitle ? 12.sp : 16.sp),
              // ),
              child: AnimatedDigitWidget(
                value: bottomCount / 1000000.0,
                textStyle: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.94),
                  fontWeight: isTitle ? FontWeight.w400 : FontWeight.w600,
                  fontSize: isTitle ? 12.sp : 16.sp,
                  letterSpacing: -0.38,
                ),
                fractionDigits: 2,
                enableSeparator: true,
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _buildWalletItemTitle(
    Widget title,
    String centerStr,
    String bottomStr,
  ) {
    return Row(
      children: [
        SizedBox(width: 70.w, child: title),
        12.horizontalSpace,
        Expanded(
          child: SizedBox(
            height: 36.w,
            child: Center(
              child: Text(
                centerStr, //.formatAmount()
                style: TextStyle(
                    color: AppColor.textPrimary.withOpacity(0.94),
                    fontWeight: FontWeight.w400,
                    fontSize: 12.sp),
              ),
            ),
          ),
        ),
        12.horizontalSpace,
        Expanded(
          child: SizedBox(
            height: 36.w,
            child: Center(
              child: Text(
                bottomStr,
                style: TextStyle(
                    color: AppColor.textPrimary.withOpacity(0.7),
                    fontWeight: FontWeight.w400,
                    fontSize: 12.sp),
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _buildRowBtn({
    required String bgIcon,
    required String icon,
    required String title,
    required Function onClick,
  }) {
    return GestureDetector(
      onTap: () {
        onClick.call();
      },
      child: Container(
        // width: 165.w,
        height: 56.w,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(
            color: AppColor.homeTabBackground,
            borderRadius: BorderRadius.circular(8.w),
            image:
                DecorationImage(image: AssetImage(bgIcon), fit: BoxFit.cover)),
        child: Row(
          children: [
            AutoImage(
              icon,
              width: 32.w,
            ),
            12.horizontalSpace,
            Text(
              title,
              style: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.94),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildItems(
      {required String icon,
      required String title,
      required Function onClick}) {
    return GestureDetector(
      onTap: () {
        onClick.call();
      },
      child: SizedBox(
        width: 90.w,
        height: 69.w,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            AutoImage(
              icon,
              width: 44.w,
            ),
            // 16.horizontalSpace,
            Text(
              title,
              style: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.7),
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w400),
            ),
          ],
        ),
      ),
    );
  }

  clickSetWithdrawAddress() {
    if (AppUserManager().user.value?.hasSetFundPassword != true) {
      CommonNormalSheet(
              title: LocaleKeys.securityTip.tr,
              child: Column(
                children: [
                  AutoImage(
                    Assets.commonSetPassword,
                    width: 80.w,
                  ),
                  32.verticalSpaceFromWidth,
                  Text(
                    LocaleKeys.accountSecurityNotice.tr,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: AppColor.textPrimary.withOpacity(0.7),
                        fontSize: 14.sp),
                  ),
                  24.verticalSpaceFromWidth,
                  Row(
                    children: [
                      Expanded(
                          child: CommonButton(
                        title: LocaleKeys.later.tr,
                        fontSize: 14.sp,
                        enable: false,
                        alwaysCanClick: true,
                        onClick: () {
                          Get.back();
                        },
                      )),
                      8.horizontalSpace,
                      Expanded(
                          child: CommonButton(
                        title: LocaleKeys.goSetPassword.tr,
                        fontSize: 14.sp,
                        onClick: () {
                          Get.back();
                          Get.toNamed(AppRoutes.profileSetPasswordPage);
                        },
                      )),
                    ],
                  ),
                  16.verticalSpaceFromWidth,
                ],
              ).marginSymmetric(horizontal: 16.w))
          .show();
    }
  }
}
